import {getRequest} from "@/utils/api";

export const initMenu = (router, store) => {
    // 仓库有菜单状态了，不要重复
    if (store.state.home.routes.length > 0) {
        return;
    }
    getRequest('/system/config/menu').then(data => {
        if (data) {
            // 后台传的菜单，不符合routes，将其格式化一下
            let fmtRoutes = formatRoutes(data);
            // 路由配置载入路由器
            fmtRoutes.forEach(route => router.addRoute(route))
            router.addRoutes(fmtRoutes);
            // 将配置存于Vuex
            store.commit('home/INIT_ROUTES', fmtRoutes);
        }
    })

}

function formatRoutes(routes) {
    let fmtRoutes = [];
    routes.forEach(route => {
        let {
            name,
            path,
            component, // 注意此处是字符串，而非我们需要的组件对象，因此要转换一下
            children,
            iconCls,
            keepAlive
        } = route;
        if (children && Array.isArray(children)) {
            // 递归 将children:[]中的routes都格式化一遍
            children = formatRoutes(children);
        }
        let fmRouter = {
            path: path,
            name: name,
            component() {
                // 一级路由的文件存放不一样
                if (component.startsWith('Home')) {
                    return import(`@/views/${component}.vue`)
                } else if (component.startsWith('Emp')) {
                    return import(`@/views/Emp/${component}.vue`)
                } else if (component.startsWith('Per')) {
                    return import(`@/views/Per/${component}.vue`)
                } else if (component.startsWith('Sal')) {
                    return import(`@/views/Sal/${component}.vue`)
                } else if (component.startsWith('Sta')) {
                    return import(`@/views/Sta/${component}.vue`)
                } else if (component.startsWith('Sys')) {
                    return import(`@/views/Sys/${component}.vue`)
                }
            },
            children: children,
            meta: {
                iconCls,
                keepAlive
            }
        }
        fmtRoutes.push(fmRouter);
    })
    return fmtRoutes;
}
